var url = require('url'),
    cofs = require('co-fs'),
    routesFolder = process.cwd() + '/routes/',
    cache = {};

module.exports = function() {
    return function* (next) {
        var originalUrl = url.parse(this.originalUrl),
            route = originalUrl.pathname.replace(/[\\|\/](.*)\..*/, '$1'),
            routeFilePath,
            isExist;

        if (!cache[route] || this.debug) {
            isExist = yield cofs.exists(routesFolder + route + '.js');

            if (isExist) {
                routeFilePath = routesFolder + route;
            } else {
                return this.status = 404;
            }
            
            cache[route] = require(routeFilePath);
        }

        try {
            this.body = yield cache[route].call(this);

            if (this.body === undefined) {
                this.redirect('/');
                this.body = '';
            }
        } catch(e) {
            this.status = 500;
        }

        yield next;
    };
};
